package org.restorator.dao.jdbc;

import com.google.common.base.Preconditions;
import org.restorator.exception.DataStoreException;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.*;

/**
 * @author Snisar Bogdan.
 */
public class SimpleResultSetExtractor
        implements ResultSetExtractor {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());


    public SimpleResultSetExtractor(RowMapper<?> mapper) {
        this.mapper = mapper;
    }

    private final RowMapper<?> mapper;

    private int rowCount;

    @Override
    public List<Object> extractData(ResultSet rs) throws DataStoreException {
        checkNotNull(rs, "Null result set");
        try {
            rowCount = 1;
            List<Object> result = new ArrayList<>();
            while (rs.next()) {
                result.add(mapper.mapRow(rs, rowCount++));
            }
            return result;
        } catch (SQLException e) {
            throw new DataStoreException(e);
        }
    }

    @Override
    public Object extractFirst(ResultSet rs) throws DataStoreException {
        checkNotNull(rs, "Null result set");
        try {
            rowCount = 1;
            if (rs.next()) {
                logger.trace("Extract first by mapper: {}", mapper);
                return mapper.mapRow(rs, rowCount);
            } else {
                logger.trace("Empty result set: !");
                return null; //todo
            }
        } catch (SQLException e) {
            throw new DataStoreException(e);
        }
    }
}
